<template>
  <el-dialog
    v-model="dialogFormVisible"
    :close-on-click-modal="false"
    :title="title"
    width="40%"
    @close="close"
  >
    <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="消息内容：" prop="content">
        <el-input
          v-model.trim="form.content"
          placeholder="请输入消息内容"
          rows="8"
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { setWeComMsg, getWeComMsg } from '@/api/enterpriseWeChat/weCom'
  export default defineComponent({
    name: 'TableMsgEdit',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        formRef: null,
        form: {
          content: '',
          open_kfid: '',
          corp_id: '',
        },
        rules: {
          content: [
            { required: true, trigger: 'blur', message: '请输入消息内容' },
          ],
        },
        title: '',
        dialogVisible: false,
        dialogFormVisible: false,
      })

      const showEdit = (corp_id, open_kfid) => {
        state.title = '设置客服欢迎语'
        state.form.corp_id = corp_id
        state.form.open_kfid = open_kfid
        getWeComMsgData()
        state.dialogFormVisible = true
      }
      const getWeComMsgData = async () => {
        const { data } = await getWeComMsg({ open_kfid: state.form.open_kfid })
        if (data) {
          state.form.content = data.content
        }
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {}
        state.dialogFormVisible = false
      }
      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { message } = await setWeComMsg(state.form)
            $baseMessage(message, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            close()
          }
        })
      }
      return {
        ...toRefs(state),
        showEdit,
        close,
        save,
      }
    },
  })
</script>
<style lang="scss" scoped></style>
